package com.ctsi.security.event.role;

import com.ctsi.commons.event.AbstractObserver;
import com.ctsi.commons.event.BaseEvent;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.framework.common.startrun.ComponentFactory;
import com.ctsi.security.PermissionRole;
import com.ctsi.security.domain.RolePermission;
import com.ctsi.security.domain.SRole;
import com.ctsi.security.service.RoleSecurityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;


public class RemoveRolePermission extends AbstractObserver {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8689138234890682427L;
	private static final Logger logger = LoggerFactory.getLogger(RemoveRolePermission.class);
	private PermissionRole sroleService;
	private RoleSecurityService roleSecurityService=(RoleSecurityService) ComponentFactory.getBean("roleSecurityService");

	@Override
	public void onEvent(Object[] args) {
		BaseEvent event=(BaseEvent) args[0];
		Map<?,?> context=event.getContext();
		RolePermission rp=context.get("rolePermissionId")==null?null:(RolePermission)context.get("rolePermissionId");
		String action=context.get("action")==null?null:(String)context.get("action");
		if(rp!=null&&"remove".equals(action)) {
			logger.info("the {} remove permission,result to remove permission to son roles!",rp.getRoleId());
			List<SRole> sons=sroleService.getSonRoles(rp.getRoleId());
			for(SRole srole :sons) {
				List<RolePermission> temp=roleSecurityService.findRolePermission(new String[] {"roleId","permissionId"}, new String[] {srole.getRoleId(),rp.getPermissionId()});
				if(UtilValidate.isNotEmpty(temp)) {
					RolePermission temprp=temp.get(0);
				//	if(!rp.getRoleId().equals(temprp.getParentRoleId())) {
				//		continue;
				//	}
					roleSecurityService.removeRolePermission(temprp.getId(), rp.getPermissionId());
				}
			}
		}
		
	}

	public void setSroleService(PermissionRole sroleService) {
		this.sroleService = sroleService;
	}
	

}
